package com.iqi.onigao;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.iqi.onigao.cache.CacheDiscreteData;
import com.iqi.onigao.config.CfgConfig;
import com.iqi.onigao.config.CfgManager;
import com.iqi.onigao.config.cfg.ItemCfg;
import com.iqi.onigao.context.BeanFactory;
import com.iqi.onigao.http.ReqData;
import com.iqi.onigao.http.RespData;
import com.iqi.onigao.http.ToolHttp;
import com.iqi.onigao.module.SIOSimpleHandler;
import com.iqi.onigao.netty.NettyClient;
import com.iqi.onigao.netty.NettySession;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.Channel;
import si.client.CUser;

public class App {
	static final Log log = LogFactory.get(App.class);
	// static String IP = "127.0.0.1:52001";
//	static String IP = "47.97.124.20:52001";
	 static String IP = "192.168.31.6:73";
	// 注册
	static String registeredUrl = "http://" + IP + "/login/user_reg";
	// 登录
	static String loginUrl = "http://" + IP + "/login/user_login";
	// 服务器
	static String SERVER_ID = "1002";
	// 账号前缀
	static String ACCOUNT_PREFIX = "SandKing";
	// 密码
	static final String PASS_WORD = "111111";

	static int max = 1;

	public static int EVENT_TIME = 5;

	public static final int limit = 20;
	
	public static final String[] cmds = new String[] {"addenergy","addexp","addtre","addmoney","addprestige"};
	
	public static final List<Integer> itemIds = new ArrayList<>();
	
	private static void init() {
		CfgManager.getInstance().init(CfgConfig.CfgFilePath, CfgConfig.fileNameMapping);
		CfgManager.getInstance().loadAllCfg();
		CacheDiscreteData.loadDiscreteData();
		
		ItemCfg.cacheCfgs.forEach((k,v)->{
			if (v.getType() == 2) {
				itemIds.add(k);				
			}
		});
	}
	
	public static void main(String[] args) throws InterruptedException {
		if (args.length == 3) {
			IP = args[0];
			SERVER_ID = args[1];
			max = Integer.valueOf(args[2]);
		}
		init();
		registeredUrl = "http://" + IP + "/login/user_reg";
		loginUrl = "http://" + IP + "/login/user_login";

		ACCOUNT_PREFIX = StrUtil.removeAll(NetUtil.getLocalMacAddress(), "-");

		log.info("IP:{} SERVER_ID:{} COUNT:{} MAC:{}", IP, SERVER_ID, max, ACCOUNT_PREFIX);

		// 初始化BeanFactory
		BeanFactory.getInstance().init(false, false);

		// 模块加载
		SIOSimpleHandler.INS.init();

		for (int i = 1; i <= max; i++) {
			final String account = ACCOUNT_PREFIX + i;
			Thread.sleep(100);
			enterLoginServer(account);
		}
	}

	public static void enterLoginServer(String account) {
		// executorService.execute(()->{
		boolean login = false;
		// 登录
		try {
			ReqData reqData = ReqData.builder().put("uName", account).put("pwd", PASS_WORD);
			RespData data = ToolHttp.post(loginUrl, reqData);
			// 没有账号 & 创建
			if (data.getCode() == 120001) {
				reqData = ReqData.builder().put("uName", account).put("pwd", PASS_WORD).put("channelNo", "robot");
				data = ToolHttp.post(registeredUrl, reqData);
				if (data.getCode() == 0) {
					data = ToolHttp.post(loginUrl, reqData);
				}
			}
			String uuid = data.getData().getStr("uuid");
			// String lastLoginServerId =
			// data.getData().getStr("lastLoginServerId",SERVER_ID);
			String accountServerId = data.getData().getStr("accountServerId");
			JSONArray districts = data.getData().getJSONArray("districts");
			for (int i = 0; i < districts.size(); i++) {
				JSONObject district = districts.getJSONObject(i);
				String serverId = district.getStr("serverId");
				if (SERVER_ID.equals(serverId)) {
					String serverIp = district.getStr("serverIp");
					int port = district.getInt("port");
					enterGameServer(account, uuid, accountServerId, serverId, serverIp, port);
					login = true;
					break;
				}
			}
			// });

		} catch (Exception e) {
			log.error(e);
		}
		if (!login) {
			enterLoginServer(account);
		}
	}

	/** 登录游戏服务器 */
	public static void enterGameServer(String account, String uuid, String accountServerId, String serverId,
			String serverIp, int port) {
		Channel channel;
		try {
			channel = NettyClient.connect(serverIp, port);
			NettySession session = new NettySession(channel, account);
			channel.attr(NettySession.sessions).set(session);
			CUser.validateUUID(session, uuid, serverId, accountServerId);
		} catch (Exception e) {
			log.error(e);
			enterLoginServer(account);
		}
	}
}
